package jsyf.oa.service.tmpevent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import jsyf.com.util.DateUtils;
import jsyf.oa.dao.attach.AttachModuleDao;
import jsyf.oa.dao.system.AuditHistoryDao;
import jsyf.oa.dao.system.MessageDao;
import jsyf.oa.dao.system.MessageReceiverDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.tmpevent.EventAuditDao;
import jsyf.oa.dao.tmpevent.EventCopierDao;
import jsyf.oa.dao.tmpevent.EventMainDao;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.attach.AttachModuleEntity;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.entity.system.AuditHistoryEntity;
import jsyf.oa.entity.system.MessageEntity;
import jsyf.oa.entity.system.MessageReceiverEntity;
import jsyf.oa.entity.system.UserEntity;
import jsyf.oa.entity.tmpEvent.EventAuditEntity;
import jsyf.oa.entity.tmpEvent.EventCopierEntity;
import jsyf.oa.entity.tmpEvent.EventEntity;
import jsyf.oa.entity.tmpEvent.EventMainEntity;
import jsyf.oa.facade.tmpevent.EventFacade;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.EVENT_AUDIT_AUDIT;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.EVENT_AUDIT_ONE;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.EVENT_AUDIT_PASS;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.EVENT_AUDIT_PASSONE;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.EVENT_AUDIT_REJECT;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.EVENT_AUDIT_REJECTONE;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.EVENT_AUDIT_THREE;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.EVENT_AUDIT_TWO;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.EVENT_COPIER_REJECT;
import static jsyf.oa.dao.wechat.service_company.TokenDao.PushTemplate.EVENT_AUDIT_NOTIFY;

@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class EventService implements EventFacade {

    @Autowired
    private EventMainDao eventMainDao;

    @Autowired
    private EventAuditDao eventAuditDao;

    @Autowired
    private EventCopierDao eventCopierDao;

    @Autowired
    private AttachModuleDao attachModuleDao;

    /**
     * 企业号服务
     */
    @Autowired
    private TokenDao tokenDao;

    @Autowired
    private AuditHistoryDao auditHistoryDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private MessageReceiverDao messageReceiverDao;

    @Override
    public JSONObject save(String jsonData) {
        JSONObject result = new JSONObject();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        EventEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), EventEntity.class);
        //第一步，保存主表信息
        EventMainEntity eventMainEntity = entity.getMain();
        eventMainEntity.setCreateTime(eventMainDao.getCurrentTime());
        eventMainEntity.setCurrentAuditorId("");
        eventMainEntity.setCurrentAuditorName("");

        if ("0".equals(eventMainEntity.getAuditFlag())) {
            //如果是提交申请，则设置当前审核人信息
            EventAuditEntity firstAuditor = entity.getAuditors().get(0);
            eventMainEntity.setCurrentAuditorId(firstAuditor.getAuditorId());
            String[] arrAuditorName = firstAuditor.getAuditorName().split("-");
            eventMainEntity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);
        }

        if (StringUtils.isBlank(eventMainEntity.getId()) || "0".equals(eventMainEntity.getId())) {
            //新建
            eventMainDao.add(eventMainEntity);
        } else {
            //编辑
            EventMainEntity oldMainEntity = eventMainDao.getEntityById(eventMainEntity.getId());
            oldMainEntity.setType(eventMainEntity.getType());
            oldMainEntity.setTitle(eventMainEntity.getTitle());
            oldMainEntity.setDescription(eventMainEntity.getDescription());
            oldMainEntity.setOrgName(eventMainEntity.getOrgName());
            oldMainEntity.setRegionName(eventMainEntity.getRegionName());
            oldMainEntity.setDescription(eventMainEntity.getDescription());
            oldMainEntity.setCreateUserId(eventMainEntity.getCreateUserId());
            oldMainEntity.setAuditFlag(eventMainEntity.getAuditFlag());
            oldMainEntity.setCreateUserName(eventMainEntity.getCreateUserName());
            oldMainEntity.setCurrentAuditorId(eventMainEntity.getCurrentAuditorId());
            oldMainEntity.setCurrentAuditorName(eventMainEntity.getCurrentAuditorName());
            eventMainDao.update(oldMainEntity);
        }

        String mainId = eventMainEntity.getId();
        if ("0".equals(eventMainEntity.getAuditFlag())) {
            //如果是提交申请，则设置当前审核人信息
            EventAuditEntity firstAuditor = entity.getAuditors().get(0);
            //企业号:给第一审核人发送消息
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", firstAuditor.getAuditorId());
            msgObject.put("content", String.format(EVENT_AUDIT_AUDIT,
                    firstAuditor.getAuditorName(),
                    eventMainEntity.getType(),
                    eventMainEntity.getTitle(),
                    eventMainEntity.getCreateUserName(),
                    DateUtils.parse(eventMainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                    eventMainEntity.getId(),
                    eventMainEntity.getCurrentAuditorId()
            ));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            //推送: 给第一审核人推送红点提示
            tokenDao.sendJPushMsg(firstAuditor.getAuditorId(), String.format(EVENT_AUDIT_NOTIFY, eventMainEntity.getCreateUserName()));

            //标记以前的审核人、申请人消息为已读
            messageReceiverRead(mainId, 0);
            messageReceiverRead(mainId, 2);

            //保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(eventMainEntity.getCreateUserId());
            messageEntity.setCreateTime(messageDao.getCurrentTime());
            messageEntity.setContent(String.format(EVENT_AUDIT_AUDIT,
                    firstAuditor.getAuditorName(),
                    eventMainEntity.getType(),
                    eventMainEntity.getTitle(),
                    eventMainEntity.getCreateUserName(),
                    DateUtils.parse(eventMainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                    eventMainEntity.getId(),
                    eventMainEntity.getCurrentAuditorId()
            ));
            messageEntity.setDelFlag(0);
            messageEntity.setMessageType(1);
            messageEntity.setMainId(mainId);
            messageEntity.setOpenUrl("/page/apply/tmpevent/detail.html?id=" + eventMainEntity.getId() + "&pageType=applyAudit&isAdd=0");
            messageEntity.setOpenTitle(String.format(EVENT_AUDIT_ONE, eventMainEntity.getCreateUserName(), eventMainEntity.getType()));
            messageDao.add(messageEntity);

            //保存第一审核人信息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(eventMainEntity.getCurrentAuditorId());
            messageReceiverEntity.setUserType(0);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);

            //发消息
            jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
        }

        //第二步，保存抄送人信息
        //删除
        eventCopierDao.removeByCondition(" AND FK_EVENT_ID = ? ", new String[]{mainId});
        //添加
        List<EventCopierEntity> eventCopierEntityList = entity.getCopiers();
        for (int i = 0; i < eventCopierEntityList.size(); i++) {
            eventCopierEntityList.get(i).setFkEventId(mainId);
            this.eventCopierDao.add(eventCopierEntityList.get(i));
        }

        //第三步，保存审核人信息
        //删除
        eventAuditDao.removeByCondition(" AND FK_EVENT_ID = ? ", new String[]{mainId});
        //添加
        List<EventAuditEntity> eventAuditEntityList = entity.getAuditors();
        if (eventAuditEntityList != null && eventAuditEntityList.size() > 0) {
            for (int i = 0; i < eventAuditEntityList.size(); i++) {
                if (!com.alibaba.dubbo.common.utils.StringUtils.isEmpty(eventAuditEntityList.get(i).getAuditorId()) && !eventAuditEntityList.get(i).getAuditorId().equals("0")) {
                    if (eventMainEntity.getAuditFlag().equals("0") && i == 0) {
                        eventAuditEntityList.get(i).setAuditFlag("0");
                    } else {
                        eventAuditEntityList.get(i).setAuditFlag("-1");
                    }
                    eventAuditEntityList.get(i).setFkEventId(mainId);
                    eventAuditEntityList.get(i).setAuditSort(i);
                    eventAuditEntityList.get(i).setAuditTime(null);
                    eventAuditEntityList.get(i).setAuditAdvise("");
                    this.eventAuditDao.add(eventAuditEntityList.get(i));
                }
            }
        }
        //第四步,保存附件
        //删除
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{mainId});
        //添加
        List<AttachmentEntity> attachmentEntityList = entity.getAttaches();
        if (attachmentEntityList != null && attachmentEntityList.size() > 0) {
            for (AttachmentEntity attach : attachmentEntityList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(4);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        result.put("message", jsonObjectList);
        result.put("mainId", mainId);
        return result;
    }

    @Override
    public String getUnDoCount(String userId) {
        Integer count = 0;
        if (userId != null && !userId.isEmpty()) {
            count = eventMainDao.getUnDoCount(userId);
        }
        return count.toString();
    }

    @Override
    public JSONObject getByPage(String userId, String key, String companyId, String auditFlag, String type, String createUserName, int requestPage, int pageSize) {
        StringBuilder condition = new StringBuilder();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (StringUtils.isNotEmpty(key)) {
            condition.append(" AND (DESCRIPTION LIKE '%" + key + "%' OR TITLE LIKE '%" + key + "%' ) ");
        }
        if (StringUtils.isNotEmpty(auditFlag)) {
            condition.append(" AND AUDIT_FLAG = ?");
            sqlArgs.add(auditFlag);
        }
        if (StringUtils.isNotEmpty(type)) {
            condition.append(" AND TYPE = ? ");
            sqlArgs.add(type);
        }
        if (StringUtils.isNotEmpty(createUserName)) {
            condition.append(" AND CREATE_USER_NAME LIKE  '%" + createUserName + "%'");
        }
        if (!StringUtils.isBlank(companyId)) {
            condition.append(" AND COMPANY_ID='" + companyId + "'");
        }
        condition.append(" AND (CREATE_USER_ID = ? ");
        condition.append(" OR ( ");
        condition.append(" AUDIT_FLAG <> '-1' ");
        condition.append(" AND ( ");
        condition.append(" ID IN(SELECT FK_EVENT_ID FROM T_TMP_EVENT_AUDIT WHERE AUDITOR_ID = ? AND AUDIT_FLAG <> '-1') ");
        condition.append(" OR ");
        //如果id是谈老板,抄送的不给他显示
        if ("2017121618514C22B68296F31AF8DDE2".equals(userId)) {
            condition.append(" ID IN(SELECT FK_EVENT_ID FROM T_TMP_EVENT_COPIER LEFT JOIN T_TMP_EVENT_MAIN ON T_TMP_EVENT_COPIER.FK_EVENT_ID = T_TMP_EVENT_MAIN.ID WHERE T_TMP_EVENT_COPIER.COPY_PERSON_ID = ? AND( T_TMP_EVENT_MAIN.AUDIT_FLAG = '2')");
            condition.append(" ) ");
        } else {
            condition.append(" ID IN(SELECT FK_EVENT_ID FROM T_TMP_EVENT_COPIER WHERE COPY_PERSON_ID = ?) ");
        }
        condition.append(" ) ");
        condition.append(" ) ");
        condition.append(" ) ");
        sqlArgs.add(userId);
        sqlArgs.add(userId);
        sqlArgs.add(userId);

        List<JSONObject> records = this.eventMainDao.getJSONListByPage(userId, condition.toString(), sqlArgs.toArray(), requestPage, pageSize);
        int recordCount = this.eventMainDao.getPageCount(condition.toString(), sqlArgs.toArray());
        int pageCount = 0;

        if (recordCount < pageSize) {
            pageCount = 1;
        } else {
            pageCount = (int) Math.ceil(recordCount / pageSize);
        }
        if (recordCount == 0) {
            pageCount = 0;
        }


        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);

        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", records);
        objResult.put("pager", objPager);
        return objResult;
    }

    @Override
    public JSONObject getById(String id) {
        EventEntity eventEntity = new EventEntity();
        eventEntity.setMain(this.eventMainDao.getEntityById(id));
        eventEntity.setCopiers(this.eventCopierDao.getEntityListByCondition(" AND FK_EVENT_ID = ? ", new Object[]{id}));
        eventEntity.setAuditors(this.eventAuditDao.getEntityListByCondition(" AND FK_EVENT_ID = ? ORDER BY AUDIT_SORT ", new Object[]{id}));
        eventEntity.setHistorys(this.auditHistoryDao.getEntityListByCondition(" AND MAIN_ID =? AND AUDIT_FLAG=2 ORDER BY AUDIT_TIME DESC", new Object[]{id}));
        return (JSONObject) JSON.toJSON(eventEntity);
    }

    @Override
    public JSONObject applyAudit(String id, String userId, String auditFlag, String advise) {
        JSONObject result = new JSONObject();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        //保存历史审核信息
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setMainId(id);
        auditHistoryEntity.setAuditorId(userId);
        JSONObject user = userDao.getJSONById(userId);
        auditHistoryEntity.setAuditorName(user.getString("name"));
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditType(2);
        auditHistoryEntity.setAuditTime(eventAuditDao.getCurrentTime());
        auditHistoryDao.add(auditHistoryEntity);
        //根据id获取主表信息
        EventMainEntity mainEntity = eventMainDao.getEntityById(id);
        //根据id获取审核信息
        List<EventAuditEntity> auditEntityList = eventAuditDao.getEntityListByCondition(" AND FK_EVENT_ID = ? ORDER BY AUDIT_SORT ", new Object[]{id});
        EventAuditEntity auditEntityNow = null;
        for (int i = 0; i < auditEntityList.size(); i++) {
            if (auditEntityList.get(i).getAuditorId().equals(userId)) {
                //如果审核人==当前审核人
                auditEntityNow = auditEntityList.get(i);
                auditEntityNow.setAuditFlag(auditFlag);
                auditEntityNow.setAuditTime(eventAuditDao.getCurrentTime());
                auditEntityNow.setAuditAdvise(advise);
                eventAuditDao.update(auditEntityNow);

                //企业号:发消息通知申请人  (不发送给抄送人)
                if ("2".equals(auditFlag)) {
                    //驳回
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", mainEntity.getCreateUserId());
                    msgObject.put("content", String.format(EVENT_AUDIT_REJECT,
                            mainEntity.getCreateUserName(),
                            mainEntity.getType(),
                            mainEntity.getTitle(),
                            auditEntityNow.getAuditAdvise(),
                            auditEntityNow.getAuditorName(),
                            DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    //企业号：审核驳回，发送消息给当前审核人(2018年09月14日09:41:17 郭琦改:不发消息给当前审核人 )
//                    JSONObject msgAuditObject = new JSONObject();
//                    msgAuditObject.put("userIds", auditEntityNow.getAuditorId());
//                    msgAuditObject.put("content", String.format(EVENT_AUDIT_REJECTONE,
//                            auditEntityNow.getAuditorName(),
//                            mainEntity.getType(),
//                            mainEntity.getCreateUserName(),
//                            DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
//                            mainEntity.getId(),
//                            mainEntity.getCurrentAuditorId()));
//                    tokenDao.sendTextMsg(JSON.toJSONString(msgAuditObject));

                    //标记以前的审核人、申请人消息为已读
                    messageReceiverRead(mainEntity.getId(), 0);
                    messageReceiverRead(mainEntity.getId(), 2);

                    //审核驳回，发送消息给申请人，保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(mainEntity.getCreateUserId());
                    messageEntity.setCreateTime(messageDao.getCurrentTime());
                    messageEntity.setDelFlag(0);
                    messageEntity.setContent(String.format(EVENT_AUDIT_REJECTONE,
                            auditEntityNow.getAuditorName(),
                            mainEntity.getType(),
                            mainEntity.getCreateUserName(),
                            DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                            mainEntity.getId(),
                            mainEntity.getCurrentAuditorId()));
                    messageEntity.setMessageType(0);
                    messageEntity.setMainId(id);
                    messageEntity.setOpenUrl("/page/apply/tmpevent/detail.html?id=" + mainEntity.getId() + "&pageType=browser&isAdd=0");
                    messageEntity.setOpenTitle(String.format(EVENT_AUDIT_THREE, mainEntity.getType(), auditEntityNow.getAuditorName()));
                    messageDao.add(messageEntity);

                    //审核驳回，发送消息给申请人,保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(mainEntity.getCreateUserId());
                    messageReceiverEntity.setUserType(2);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);

                    //发消息1
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                }

                if ("1".equals(auditFlag)) {

                    //企业号：审核通过，发送消息给当前审核人
//                    JSONObject msgAuditObject = new JSONObject();
//                    msgAuditObject.put("userIds", auditEntityNow.getAuditorId());
//                    msgAuditObject.put("content", String.format(EVENT_AUDIT_PASSONE,
//                            auditEntityNow.getAuditorName(),
//                            mainEntity.getType(),
//                            mainEntity.getCreateUserName(),
//                            DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
//                            mainEntity.getId(),
//                            mainEntity.getCurrentAuditorId()));
//                    tokenDao.sendTextMsg(JSON.toJSONString(msgAuditObject));

                    //标记以前的审核人消息为已读
                    messageReceiverRead(mainEntity.getId(), 0);

//                    //审核通过，发送消息给审核人，保存消息到消息表t_sys_message
//                    MessageEntity msgAuditEntity = new MessageEntity();
//                    msgAuditEntity.setCreateUserId(mainEntity.getCreateUserId());
//                    msgAuditEntity.setCreateTime(messageDao.getCurrentTime());
//                    msgAuditEntity.setDelFlag(0);
//                    msgAuditEntity.setContent(String.format(EVENT_AUDIT_PASSONE,
//                            auditEntityNow.getAuditorName(),
//                            mainEntity.getType(),
//                            mainEntity.getCreateUserName(),
//                            DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
//                            mainEntity.getId(),
//                            mainEntity.getCurrentAuditorId()));
//                    msgAuditEntity.setMessageType(0);
//                    msgAuditEntity.setMainId(id);
//                    msgAuditEntity.setOpenUrl("/page/apply/tmpevent/detail.html?id=" + mainEntity.getId() + "&pageType=browser&isAdd=0");
//                    msgAuditEntity.setOpenTitle(String.format(EVENT_AUDIT_FOUR, mainEntity.getCreateUserName(), mainEntity.getType()));
//                    messageDao.add(msgAuditEntity);
//
//                    //审核通过，发送消息给审核人，保存消息到表t_sys_message_receiver
//                    MessageReceiverEntity msgReceiverEntity = new MessageReceiverEntity();
//                    msgReceiverEntity.setMessageId(msgAuditEntity.getId());
//                    msgReceiverEntity.setUserId(auditEntityNow.getAuditorId());
//                    msgReceiverEntity.setUserType(0);
//                    msgReceiverEntity.setReadFlag(0);
//                    messageReceiverDao.add(msgReceiverEntity);
//
//                    //发消息2
//                    jsonObjectList.add(getMessage(msgAuditEntity, msgReceiverEntity));

                    if (i == auditEntityList.size() - 1) {
                        //如果是最后一个审核人
                        mainEntity.setAuditFlag(auditFlag);
                        mainEntity.setCurrentAuditorId("");
                        mainEntity.setCurrentAuditorName("");
                        eventMainDao.update(mainEntity);

                        //企业号: 最后一个审核通过,发送消息给申请人
                        JSONObject msgObject = new JSONObject();
                        msgObject.put("userIds", mainEntity.getCreateUserId());
                        msgObject.put("content", String.format(EVENT_AUDIT_PASS,
                                mainEntity.getCreateUserName(),
                                mainEntity.getType(),
                                auditEntityNow.getAuditorName(),
                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                        //标记以前的审核人、申请人消息为已读
                        messageReceiverRead(mainEntity.getId(), 0);
                        messageReceiverRead(mainEntity.getId(), 2);

                        //最后一个审核通过，发送消息给申请人，保存消息到消息表t_sys_message
                        MessageEntity messageEntity = new MessageEntity();
                        messageEntity.setCreateUserId(mainEntity.getCreateUserId());
                        messageEntity.setCreateTime(messageDao.getCurrentTime());
                        messageEntity.setDelFlag(0);
                        messageEntity.setContent(String.format(EVENT_AUDIT_PASS,
                                mainEntity.getCreateUserName(),
                                mainEntity.getType(),
                                auditEntityNow.getAuditorName(),
                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));
                        messageEntity.setMessageType(0);
                        messageEntity.setMainId(id);
                        messageEntity.setOpenUrl("/page/apply/tmpevent/detail.html?id=" + mainEntity.getId() + "&pageType=browser&isAdd=0");
                        messageEntity.setOpenTitle(String.format(EVENT_AUDIT_TWO, mainEntity.getType(), auditEntityNow.getAuditorName()));
                        messageDao.add(messageEntity);

                        //最后一个审核通过，发送消息给申请人，保存消息到表t_sys_message_receiver
                        MessageReceiverEntity msgEntity = new MessageReceiverEntity();
                        msgEntity.setMessageId(messageEntity.getId());
                        msgEntity.setUserId(mainEntity.getCreateUserId());
                        msgEntity.setUserType(2);
                        msgEntity.setReadFlag(0);
                        messageReceiverDao.add(msgEntity);

                        //发消息3
                        jsonObjectList.add(getMessage(messageEntity, msgEntity));

                    } else {
                        EventAuditEntity auditEntityNext = auditEntityList.get(i + 1);
                        auditEntityNext.setAuditFlag("0");
                        eventAuditDao.update(auditEntityNext);

                        mainEntity.setCurrentAuditorId(auditEntityNext.getAuditorId());
                        String[] arrAuditorName = auditEntityNext.getAuditorName().split("-");
                        mainEntity.setCurrentAuditorName(arrAuditorName[arrAuditorName.length - 1]);
                        eventMainDao.update(mainEntity);

                        //企业号: 审核通过,发送消息给申请人
                        JSONObject msgObject = new JSONObject();
                        msgObject.put("userIds", mainEntity.getCreateUserId());
                        msgObject.put("content", String.format(EVENT_AUDIT_PASS,
                                mainEntity.getCreateUserName(),
                                mainEntity.getType(),
                                auditEntityNow.getAuditorName(),
                                DateUtils.parse(auditEntityNow.getAuditTime(), "yyyy-MM-dd HH:mm")));

                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                        //标记以前的审核人消息为已读
                        messageReceiverRead(mainEntity.getId(), 2);

                        //审核通过,发送消息给申请人,保存消息到消息表t_sys_message
                        MessageEntity messageEntity = new MessageEntity();
                        messageEntity.setCreateUserId(mainEntity.getCreateUserId());
                        messageEntity.setCreateTime(messageDao.getCurrentTime());
                        messageEntity.setDelFlag(0);
                        messageEntity.setContent(String.format(EVENT_AUDIT_PASSONE,
                                mainEntity.getCreateUserName(),
                                "你提交的临时事项\n" + mainEntity.getType(),
                                mainEntity.getTitle(),
                                mainEntity.getCurrentAuditorName(),
                                DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                                mainEntity.getId(),
                                mainEntity.getCurrentAuditorId()
                        ));
                        messageEntity.setMessageType(1);
                        messageEntity.setMainId(id);
                        messageEntity.setOpenUrl("/page/apply/tmpevent/detail.html?id=" + mainEntity.getId() + "&pageType=applyAudit&isAdd=0");
                        messageEntity.setOpenTitle(String.format(EVENT_AUDIT_TWO, mainEntity.getType(), auditEntityNow.getAuditorName()));
                        messageDao.add(messageEntity);

                        //保存消息到消息收件人表t_sys_message_receiver
                        MessageReceiverEntity messageCreateReceiverEntity = new MessageReceiverEntity();
                        messageCreateReceiverEntity.setMessageId(messageEntity.getId());
                        messageCreateReceiverEntity.setUserId(mainEntity.getCreateUserId());
                        messageCreateReceiverEntity.setUserType(2);
                        messageCreateReceiverEntity.setReadFlag(0);
                        messageReceiverDao.add(messageCreateReceiverEntity);

                        //发消息4
                        jsonObjectList.add(getMessage(messageEntity, messageCreateReceiverEntity));

                        //企业号: 给下一审核人发消息
                        JSONObject msgNextObject = new JSONObject();
                        msgNextObject.put("userIds", auditEntityNext.getAuditorId());
                        msgNextObject.put("content", String.format(EVENT_AUDIT_AUDIT,
                                auditEntityNext.getAuditorName(),
                                mainEntity.getType(),
                                mainEntity.getTitle(),
                                mainEntity.getCreateUserName(),
                                DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                                mainEntity.getId(),
                                mainEntity.getCurrentAuditorId()
                        ));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));

                        //推送: 给下一审核人推送红点提示
                        tokenDao.sendJPushMsg(auditEntityNext.getAuditorId(), String.format(EVENT_AUDIT_NOTIFY, mainEntity.getCreateUserName()));

                        //给下一审核人发消息，保存消息到消息表t_sys_message
                        MessageEntity messageNextEntity = new MessageEntity();
                        messageNextEntity.setCreateUserId(mainEntity.getCreateUserId());
                        messageNextEntity.setCreateTime(messageDao.getCurrentTime());
                        messageNextEntity.setDelFlag(0);
                        messageNextEntity.setContent(String.format(EVENT_AUDIT_AUDIT,
                                auditEntityNext.getAuditorName(),
                                mainEntity.getType(),
                                mainEntity.getTitle(),
                                mainEntity.getCreateUserName(),
                                DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                                mainEntity.getId(),
                                mainEntity.getCurrentAuditorId()
                        ));
                        messageNextEntity.setMessageType(1);
                        messageNextEntity.setMainId(id);
                        messageNextEntity.setOpenUrl("/page/apply/tmpevent/detail.html?id=" + mainEntity.getId() + "&pageType=applyAudit&isAdd=0");
                        messageNextEntity.setOpenTitle(String.format(EVENT_AUDIT_ONE, mainEntity.getCreateUserName(), mainEntity.getType()));
                        messageDao.add(messageNextEntity);

                        //保存消息到消息收件人表t_sys_message_receiver
                        MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                        messageReceiverEntity.setMessageId(messageNextEntity.getId());
                        messageReceiverEntity.setUserId(mainEntity.getCurrentAuditorId());
                        messageReceiverEntity.setUserType(0);
                        messageReceiverEntity.setReadFlag(0);
                        messageReceiverDao.add(messageReceiverEntity);

                        //发消息5
                        jsonObjectList.add(getMessage(messageNextEntity, messageReceiverEntity));

                    }
                } else {
                    mainEntity.setAuditFlag(auditFlag);
                    mainEntity.setCurrentAuditorId("");
                    mainEntity.setCurrentAuditorName("");
                    eventMainDao.update(mainEntity);
                }
                break;
            }
        }
        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    @Override
    public Boolean removeById(String id) {
        return eventMainDao.removeById(id) > 0;
    }

    @Override
    public JSONObject copierReturn(String id, String copierReturnReason) {
        JSONObject result = new JSONObject();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        boolean success = eventMainDao.copierReturn(id, copierReturnReason) > 0;
        if (success) {
            //企业号 抄送人驳回
            EventMainEntity mainEntity = eventMainDao.getEntityById(id);
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", mainEntity.getCreateUserId());
            msgObject.put("content", String.format(EVENT_COPIER_REJECT,
                    mainEntity.getCreateUserName(),
                    mainEntity.getType(),
                    mainEntity.getTitle(),
                    mainEntity.getCopierReturnReason()));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

            //标记以前的审核人、申请人消息为已读
            messageReceiverRead(mainEntity.getId(), 0);
            messageReceiverRead(mainEntity.getId(), 2);

            //给抄送人,保存消息到消息表t_sys_message
            MessageEntity messageNextEntity = new MessageEntity();
            messageNextEntity.setCreateUserId(mainEntity.getCreateUserId());
            messageNextEntity.setCreateTime(messageDao.getCurrentTime());
            messageNextEntity.setDelFlag(0);
            messageNextEntity.setContent(String.format(EVENT_AUDIT_REJECTONE,
                    mainEntity.getCreateUserName(),
                    mainEntity.getType(),
                    mainEntity.getTitle(),
                    mainEntity.getCreateUserName(),
                    DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm"),
                    mainEntity.getId(),
                    mainEntity.getCurrentAuditorId()
            ));
            messageNextEntity.setMessageType(0);
            messageNextEntity.setMainId(id);
            messageNextEntity.setOpenUrl("/page/apply/tmpevent/detail.html?id=" + mainEntity.getId() + "&pageType=applyAudit&isAdd=0");
            messageNextEntity.setOpenTitle(String.format(EVENT_AUDIT_THREE, mainEntity.getType()));
            messageDao.add(messageNextEntity);

            //保存消息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageNextEntity.getId());
            messageReceiverEntity.setUserId(mainEntity.getCreateUserId());
            messageReceiverEntity.setUserType(2);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);

            //发消息6
            jsonObjectList.add(getMessage(messageNextEntity, messageReceiverEntity));
        }
        result.put("message", jsonObjectList);
        result.put("flag", success);
        return result;
    }

    @Override
    public JSONObject getFirstAuditor() {

        return eventAuditDao.getFirstParent();
    }

    private JSONObject getMessage(MessageEntity messageEntity, MessageReceiverEntity messageReceiverEntity) {
        String userId = messageEntity.getCreateUserId();
        UserEntity userEntity = userDao.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", messageEntity.getId());
        jsonObject.put("createUserId", userId);
        jsonObject.put("createUserName", userEntity.getName());
        jsonObject.put("delFlag", messageEntity.getDelFlag());
        jsonObject.put("createTime", messageEntity.getCreateTime());
        jsonObject.put("content", messageEntity.getContent());
        jsonObject.put("mainId", messageEntity.getMainId());
        jsonObject.put("openTitle", messageEntity.getOpenTitle());
        jsonObject.put("openUrl", messageEntity.getOpenUrl());
        jsonObject.put("messageType", messageEntity.getMessageType());
        jsonObject.put("receiverId", messageReceiverEntity.getId());
        jsonObject.put("receiverUserId", messageReceiverEntity.getUserId());
        jsonObject.put("receiverUserType", messageReceiverEntity.getUserType());
        jsonObject.put("receiverReadFlag", messageReceiverEntity.getReadFlag());
        return jsonObject;
    }

    //标记消息为已读 /0-审核人 /2-申请人 /1-抄送人(暂无)
    private void messageReceiverRead(String mainId, Integer userType) {
        StringBuffer sb = new StringBuffer();
        List<String> arg = new ArrayList<>();
        if (!StringUtils.isBlank(mainId)) {
            sb.append("AND mainId=?");
            arg.add(mainId);
        }
        if (null != userType) {
            sb.append("AND receiverUserType=?");
            arg.add(userType.toString());
        }
        String receiverIds = "";
        List<JSONObject> jsonObjectList = messageDao.getViewJSONListByCondition(sb.toString(), arg.toArray());
        if (null != jsonObjectList && jsonObjectList.size() > 0) {
            for (int i = 0; i < jsonObjectList.size(); i++) {
                receiverIds += "'" + jsonObjectList.get(i).getString("receiverId") + "',";
            }
        }
        if (receiverIds.length() > 1) {
            receiverIds = receiverIds.substring(0, receiverIds.length() - 1);
        } else {
            receiverIds = null;
        }
        if (!StringUtils.isBlank(receiverIds)) {
            messageReceiverDao.updateReadFlag("T_SYS_MESSAGE_RECEIVER", "AND ID IN (" + receiverIds + ")");
        }
    }

}
